const os = require( 'os' );
const fs = require( 'fs' );
const path = require( 'path' );
const readline = require( 'readline' );

const moment = require( 'moment' );
const express = require( 'express' );

const rl = readline.createInterface( {
    input: fs.createReadStream( './log/2020-11-11.log' )
} );
let i = 0;
rl.on( 'line', function ( line ) { 
    i++;
    console.log( i );
} )

const app = express();
const webRootpath = path.join( __dirname );

let now = moment().format( 'YYYY-MM-DD' );
const filepath = path.join( __dirname, 'log', now + '.log' );
let count = 0;
app.use( ( req, res, next ) => { 
    let userAgent = req.headers[ 'user-agent' ];
    if ( /^Chrom*/g.test( userAgent ) ) {
        console.log( '浏览器是谷歌' );
    } else if ( /^Mozilla*/g.test( userAgent ) ) {
        console.log('浏览器是火狐');
    }
    next();
})

// let pathname;
app.use( function ( req, res ) {

    let tt = moment().format( 'YYYY-MM-DD hh:mm:ss' );
    let ip = req.socket.remoteAddress;
    let userAgent = req.headers[ 'user-agent' ];
    let data = `${ tt }-${ ip }-${ userAgent }${ os.EOL }`;

    let pathname = req.url;
    let webfilepath = path.join( webRootpath, pathname );
    let extname = path.extname( webfilepath );
    if ( extname === '.html' ) {
        fs.appendFile( filepath, data, err => {} );
    } else {
        return;
    }
    res.send( `一共访问${i}次`  )
} )
app.listen( 8080 );